package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.User2;
import com.cskaoyan.bean.UserData;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.exception.ValidationException;
import com.cskaoyan.service.UserService;
import com.cskaoyan.util.ValidationUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.Binding;

/**
 * @author stone
 * @date 2022/01/06 16:23
 */
@RestController
public class UserController {

    @Autowired
    UserService userService;

    // 注解的value属性是字符串数组：该url可以绑定多个权限，多个权限之间的关系 → 由logical属性决定，默认值是and
    @RequiresPermissions(value = {"admin:user:list","songge"},logical = Logical.OR)
    @RequestMapping("admin/user/list")
    public BaseRespVo userList(String username,BaseParam param) {
        UserData userData = userService.query(param,username);
        return BaseRespVo.ok(userData);
    }

    //localhost:8083/admin/user/list2?username=songge&password=niupi
    @RequestMapping("admin/user/list2")
    public BaseRespVo userList2(@Validated User2 user2,BindingResult bindingResult) {
        // 成员变量是否有错误 → 请求参数是否合法 → true 不合法
        //只要有一个成员变量有错误，返回值则为true
        if (bindingResult.hasFieldErrors()) {
            // 拿到成员变量的错误
            FieldError fieldError = bindingResult.getFieldError();
            // 不合法的值是什么
            Object rejectedValue = fieldError.getRejectedValue();
            // 成员变量名 → 请求参数名
            String field = fieldError.getField();
            // 默认的消息
            String defaultMessage = fieldError.getDefaultMessage();
            String msg = "请求参数" + field + "因为传入了值" + rejectedValue + "没有通过校验：" + defaultMessage;
            return BaseRespVo.invalidParameter(msg);
        }
        return BaseRespVo.ok(null);

    }
    @RequestMapping("admin/user/list3")
    public BaseRespVo userList3(@Validated User2 user2,BindingResult bindingResult) {
        // 成员变量是否有错误 → 请求参数是否合法 → true 不合法
        //只要有一个成员变量有错误，返回值则为true
        if (bindingResult.hasFieldErrors()) {
            //ctrl + alt + m
            return ValidationUtil.valid(bindingResult);
        }
        return BaseRespVo.ok(null);

    }

    @RequestMapping("admin/user/list4")
    public BaseRespVo userList4(@Validated User2 user2,BindingResult bindingResult) throws ValidationException {
        // 如果校验没有通过，响应BaseRespVo.invalidParameter(msg);
        ValidationUtil.valid2(bindingResult);

        return BaseRespVo.ok(null);

    }


}
